from appium import webdriver
from time import sleep
import random

from appium.webdriver.common.touch_action import TouchAction

desired_caps = dict()
desired_caps['platformName'] = 'Android'
desired_caps['platformVersion'] = '5.1'
desired_caps['deviceName'] = 'moniqi'
# 设置
desired_caps['appPackage'] = 'com.android.settings'
desired_caps['appActivity'] = '.Settings'
# 通讯录
# desired_caps['appPackage'] = 'com.android.contacts'
# desired_caps['appActivity'] = '.activities.PeopleActivity'
# 文件管理
# desired_caps['appPackage'] = 'com.cyanogenmod.filemanager'
# desired_caps['appActivity'] = '.activities.NavigationActivity'
desired_caps['unicodeKeyboard'] = True
desired_caps['resetKeyboard'] = True
driver = webdriver.Remote('http://localhost:4723/wd/hub', desired_caps)
"""需求1:从起始点位2000,200的位置,滑动到100,500的位置,持续时间8秒"""
# driver.swipe(2000, 200, 1000, 500, 8000)
# driver.swipe(100, 500, 100, 200, 8000)

"""需求2:从"存储"这个元素的中心点,滑动到100,100的位置"""
# x = driver.find_element_by_xpath("//*[@text='存储']").location["x"]
# y = driver.find_element_by_xpath("//*[@text='存储']").location["y"]
# w = driver.find_element_by_xpath("//*[@text='存储']").size["width"]
# h = driver.find_element_by_xpath("//*[@text='存储']").size["height"]
# driver.swipe(x + w * 0.5, y + h * 0.5, 100, 100)
# # driver.swipe(x + w 0.5, y + h * 0.5, 100, 100, 3000)

"""需求3:滑动并寻找"关于平板电脑",并点进去"""

# 封装'寻找并点击'方法:
# def find_click(cont, times=1000, fre=10):
#     import time
#     num = 0
#     while True:
#         li = driver.find_elements_by_id("com.android.settings:id/title")
#         li1 = []
#         for i in li:
#             # print(i.text)
#             li1.append(i.text)
#         print(li1)
#         if cont not in li1:
#             driver.swipe(350, 1000, 350, 300, times)
#         else:
#             ele = driver.find_element_by_xpath("//*[@text='%s']" % cont)
#             TouchAction(driver).tap(ele).perform()
#             break
#         num += 1
#         if num >= fre:
#             break
#
#
# # 调用寻找并点击方法,以3000毫秒滑动速度寻找'关于平板电脑'并点击,如果5次滑动没有找到元素,结束
# find_click("电池", 3000, 5)

"""try实现"""

# while True:
#     try:
#         driver.find_element_by_xpath("//*[@text='关于平板电脑']").click()
#         break
#     except Exception:
#         driver.swipe(350, 1000, 350, 2000)


"""for-else 语法实现"""


def find_click():
    while True:
        li = driver.find_elements_by_id("com.android.settings:id/title")
        for i in li:
            if i.text == "关于平板电脑":
                i.click()
                return
        else:
            driver.swipe(350, 1000, 350, 100, 2000)


find_click()

sleep(3)
driver.quit()
